<script setup>
/** https://blog.csdn.net/lhkuxia/article/details/117597616 */
import {
  ref,
  getCurrentInstance,
  watch,
  defineProps,
  onMounted,
  nextTick,
} from "vue";
import { Message } from "element-ui";

import commonJs from "@/assets/js/common.js";
import { useActivitiInfo } from "@/components/Activiti/ApprovalInfo/hooks/use-activiti-info.js";

import VForm from "@/components/VForm/index.vue";
import Layout from "@/components/Activiti/ApprovalInfo/layout/Layout.vue";

// TODO
// getReadOnlyActivitiInfo

import { add } from "@/api/activiti/leaveTest.js";

const props = defineProps({
  /** 实例id 由路由提供的id值 */
  instanceId: { type: String },

  /** 业务id */
  businessKey: { type: String },

  /** 任务id 每一个待办任务的id */
  taskId: { type: String },

  /** 业务单据 */
  module: { type: String },
});

const {
  hasStartActiviti,
  activitiInfoComputed,
  isCurrentUserHasTodoTask,
  canShowAside,
  isAdd,
  isUnstart,
  startActivitiProcess,
} = useActivitiInfo();

/** 本组件内可用的 只读的 工作流实例 */
const activitiInfo = activitiInfoComputed;

const isLoading = ref(false);

const formVue = ref(null);

/** 可以设置的 业务id */
// const canSetBusinessId = ref("");

const toLayoutInstanceId = ref(props.instanceId);
const toLayoutBusinessId = ref(props.businessKey);

const conf = {
  tabsRenderList: [],
};

// 字典
const dictRadioOptions = ref([]);
const dictCheckboxOptions = ref([]);
const dictSelectOptions = ref([]);

commonJs.filterDataDict("sex", dictRadioOptions.value);
commonJs.filterDataDict("useState", dictCheckboxOptions.value);
commonJs.filterDataDict("useState", dictSelectOptions.value);

// const form = ref({
//   name: "",
//   num: "",
//   sendTime: "",
//   dictRadio: "",
//   dictSelect: "",
//   remark: "",
//   pic: [],
//   file: [],
//   dictCheckbox: [],
// });

/** @type { import("@/types/BizLeaveAdd").BizLeaveAdd } */
const bizLeaveAdd = {
  applyTime: "",
  applyUserId: "",
  applyUserName: "",
  createBy: "",
  createTime: "",
  delFlag: "",
  // 在本组件内 默认的初始值就是null 未提交值时 id为null
  id: null,
  instanceId: "",
  leaveEndTime: "",
  leaveStartTime: "",
  processKey: "",
  realityEndTime: "",
  realityStartTime: "",
  reason: "",
  remark: "",
  suspendState: "",
  suspendStateName: "",
  taskId: "",
  taskName: "",
  title: "",
  totalTime: 0,
  type: "",
  updateBy: "",
  updateTime: "",
};

// 该类型声明有误
// /** @type { import("vue").Ref< import("@/types/BizLeaveAdd").BizLeaveAdd > } */
const form = ref(bizLeaveAdd);

// FormRules
// /** @type {  } */
const rules = {
  type: [{ required: true, message: "请假类型不能为空", trigger: "blur" }],
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  reason: [{ required: true, message: "原因不能为空", trigger: "blur" }],
  leaveStartTime: [
    { required: true, message: "开始时间不能为空", trigger: "blur" },
  ],
  leaveEndTime: [
    { required: true, message: "结束时间不能为空", trigger: "blur" },
  ],
};

const typeOptions = ref([
  { dictLabel: "年假", dictValue: "1" },
  { dictLabel: "事假", dictValue: "2" },
  { dictLabel: "病假", dictValue: "3" },
]);

const formData = ref({
  labelWidth: "100px",
  options: [
    {
      title: "名称",
      key: "name",
      type: "text",
    },
    {
      title: "数量",
      key: "num",
      type: "text",
    },
    {
      title: "发送日期",
      key: "sendTime",
      type: "date",
    },
    {
      title: "图片",
      key: "pic",
      type: "file",
      fileType: "image",
      listType: "picture-card",
      uploadTextTip: "",
    },
    {
      title: "文件",
      key: "file",
      type: "file",
      fileType: "file",
      listType: "text",
      uploadTextTip: "",
    },
    {
      title: "字典radio",
      key: "dictRadio",
      type: "radio",
      option: {
        data: dictRadioOptions.value,
        props: {
          key: "id", // 指定key对应data的字段
          label: "label", // 指定label对应data的字段
          value: "value", // 指定value对应data的字段
        },
      },
    },
    {
      title: "字典checkBox",
      key: "dictCheckbox",
      type: "checkbox",
      option: {
        data: dictCheckboxOptions.value,
        props: {
          key: "id", // 指定key对应data的字段
          label: "label", // 指定label对应data的字段
        },
      },
    },
    {
      title: "字典select",
      key: "dictSelect",
      type: "select",
      multiple: false,
      option: {
        data: dictSelectOptions.value,
        props: {
          key: "id", // 指定key对应data的字段
          label: "label", // 指定label对应data的字段
          value: "value", // 指定value对应data的字段
        },
      },
    },
    {
      title: "备注",
      key: "remark",
      type: "textarea",
    },
  ],
  rules: {
    name: [
      { required: true, message: "请输入", trigger: "blur" },
      { max: 64, message: "长度最大为64个字符", trigger: "blur" },
    ],
    num: [{ required: true, message: "请输入", trigger: "blur" }],
    sendTime: [{ required: true, message: "请输入", trigger: "blur" }],
    pic: [],
    file: [],
    dictRadio: [],
    dictCheckbox: [],
    dictSelect: [{ required: true, message: "请选择", trigger: "change" }],
    remark: [{ max: 255, message: "长度最大为255个字符", trigger: "blur" }],
  },
});

// 不考虑在vue2.7的setup内，监听实例提供的路由对象。做不到。太乱了。
const { proxy: currentVueInstance } = getCurrentInstance();
const { $route } = currentVueInstance;

/** 新增 业务数据 */
async function addBusinessData() {
  isLoading.value = true;

  await add(form.value)
    .then((res) => {
      const data = res.data;
      // 接口返回undefined 无任何内容提示
      console.log(" 新增业务数据 ", data);

      // 从新增接口中，获取到返回的id字段 获取到业务id值
      toLayoutBusinessId.value = data;
    })
    .catch()
    .finally(() => (isLoading.value = true));
}

/** 表单提交 */
async function submitForm() {
  await nextTick(() => {
    formVue.value.validate(async (valid) => {
      // 检查是否检验通过
      if (valid) {
        if (form.value.id !== null) {
          // TODO:
          // 需要调用修改接口
          // update(this.form).then((response) => {
          //   this.$message.success("修改成功");
          //   this.open = false;
          //   this.getList();
          // });
        } else {
          await addBusinessData();
          // add(this.form).then((response) => {
          //   this.$message.success("新增成功");
          //   this.open = false;
          //   this.getList();
          // });
        }
      } else {
        Message.warning({ message: "请重新检查表单" });
      }
    });
  });
}

/** 启动工作流 */
async function startProcess() {
  await startActivitiProcess({
    module: "biz_leave",
    processKey: "leave",
    // TODO:
    dataId: "",
    title: "",
    variables: {},
  })
    .then((res) => {
      console.log(" 完成启动 ", res);
    })
    .catch()
    .finally();
}
</script>

<template>
  <section class="ActivitiInfo-page-root">
    <Layout
      :conf="conf"
      :instance-id="instanceId"
      :business-key="businessKey"
      :task-id="taskId"
      :module="module"
    >
      <!-- 位于标题位置的 专用于用户自定义按钮的插槽 -->
      <template #titleButton>
        <el-button
          type="primary"
          size="default"
          v-show="isAdd"
          @click="submitForm()"
        >
          新增申请
        </el-button>

        <el-button
          type="primary"
          size="default"
          v-show="isUnstart"
          @click="startProcess()"
        >
          发起审批
        </el-button>
      </template>

      <!-- 暂时不使用插槽提供的值 activitiInfo -->
      <template #baseInfo>
        <!-- 测试 可以对外返回出数据 -->
        <el-tag type="danger" size="normal" effect="dark" v-if="false">
          {{ activitiInfo.componentsStatus }}
        </el-tag>

        <el-form ref="formVue" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="请假类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择请假类型">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>

          <el-form-item label="原因" prop="reason">
            <el-input
              v-model="form.reason"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>

          <el-form-item label="开始时间" prop="leaveStartTime">
            <el-date-picker
              clearable
              size="small"
              style="width: 200px"
              v-model="form.leaveStartTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择开始时间"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="结束时间" prop="leaveEndTime">
            <el-date-picker
              clearable
              size="small"
              style="width: 200px"
              v-model="form.leaveEndTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择结束时间"
            >
            </el-date-picker>
          </el-form-item>

          <!--<el-form-item label="请假时长" prop="totalTime">
          <el-input v-model="form.totalTime" readonly />
        </el-form-item>-->

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-form>

        <!-- TODO: 开始模拟用户自己的表单组件 不使用 -->
        <VForm
          v-if="false"
          ref="vformComponents"
          :rules="formData.rules"
          :options="formData.options"
          :form="form"
          :labelWidth="formData.labelWidth"
          :rowspan="1"
        >
        </VForm>
      </template>
    </Layout>
  </section>
</template>

<style lang="scss" scoped>
.ActivitiInfo-page-root {
  width: 100%;

  // height: 100%;
  // 用于模拟工作流组件 在高度不够的页面的显示效果
  height: 90%;
}
</style>
